﻿' ----------------------------------------------------------------------------------
' Microsoft Developer & Platform Evangelism
' 
' Copyright (c) Microsoft Corporation. All rights reserved.
' 
' THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
' EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
' OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
' ----------------------------------------------------------------------------------
' The example companies, organizations, products, domain names,
' e-mail addresses, logos, people, places, and events depicted
' herein are fictitious.  No association with any real company,
' organization, product, domain name, email address, logo, person,
' places, or events is intended or should be inferred.
' ----------------------------------------------------------------------------------

Imports Microsoft.WindowsAzure
Imports Microsoft.Samples.WindowsPhoneCloud.Web.Serializers
Imports Microsoft.Samples.WindowsPhoneCloud.Web.Infrastructure
Imports System.Net
Imports System.Globalization

Namespace Handlers

    Public Class AzureQueuesProxyHandler
        Inherits StorageProxyHandler
        Private ReadOnly userPrivilegesRepository As IUserPrivilegesRepository

#If ACS Then
		Public Sub New()
			Me.New(New UserTablesServiceContext(), CloudStorageAccount.FromConfigurationSetting("DataConnectionString"), New FormatSerializerFactory())
		End Sub

		<CLSCompliant(False)>
		Public Sub New(ByVal userPrivilegesRepository As IUserPrivilegesRepository, ByVal cloudStorageAccount As CloudStorageAccount, ByVal formatSerializerFactory As IFormatSerializerFactory)
			MyBase.New(cloudStorageAccount, formatSerializerFactory)
			Me.userPrivilegesRepository = userPrivilegesRepository
		End Sub
#Else
        Public Sub New()
            Me.New(New UserTablesServiceContext(), CloudStorageAccount.FromConfigurationSetting("DataConnectionString"), New QueueRequestValidator(), New FormatSerializerFactory())
        End Sub

        <CLSCompliant(False)>
        Public Sub New(ByVal userPrivilegesRepository As IUserPrivilegesRepository, ByVal cloudStorageAccount As CloudStorageAccount, ByVal requestValidator As IStorageRequestValidator, ByVal formatSerializerFactory As IFormatSerializerFactory)
            MyBase.New(cloudStorageAccount, requestValidator, formatSerializerFactory)
            Me.userPrivilegesRepository = userPrivilegesRepository
        End Sub
#End If

        Protected Overrides ReadOnly Property AzureStorageUrl() As String
            Get
                Return Me.CloudStorageAccount.QueueEndpoint.ToString().TrimEnd("/"c)
            End Get
        End Property

        Protected Overrides Sub SignRequest(ByVal webRequest As WebRequest)
            Dim httpWebRequest = TryCast(webRequest, HttpWebRequest)
            If httpWebRequest IsNot Nothing Then
                Me.CloudStorageAccount.Credentials.SignRequest(httpWebRequest)
            End If
        End Sub

#If ACS Then
		Protected Overrides Sub PostProcessProxyRequest(ByVal context As HttpContext)
			Dim queueName = StorageRequestAnalyzer.GetRequestedQueue(context.Request)

			If (context.Response.StatusCode = CInt(HttpStatusCode.Created)) AndAlso StorageRequestAnalyzer.IsCreatingQueue(context.Request) Then
				' A new queue was created -> add permissions to the current user.
				Me.AddQueuePermissions(queueName, Me.UserId)
			ElseIf (context.Response.StatusCode = CInt(HttpStatusCode.NoContent)) AndAlso StorageRequestAnalyzer.IsDeletingQueue(context.Request) Then
				' A queue was deleted -> remove all permissions to that queue.
				Me.RemoveAllQueuePermissions(queueName)
			End If
		End Sub
#Else
        Protected Overrides Sub PostProcessProxyRequest(ByVal context As HttpContext)
            Dim queueName = StorageRequestAnalyzer.GetRequestedQueue(context.Request)

            If (context.Response.StatusCode = CInt(HttpStatusCode.Created)) AndAlso StorageRequestAnalyzer.IsCreatingQueue(context.Request) Then
                ' A new queue was created -> add permissions to the current user.
                Me.AddQueuePermissions(queueName, Me.RequestValidator.GetUserId(context))
            ElseIf (context.Response.StatusCode = CInt(HttpStatusCode.NoContent)) AndAlso StorageRequestAnalyzer.IsDeletingQueue(context.Request) Then
                ' A queue was deleted -> remove all permissions to that queue.
                Me.RemoveAllQueuePermissions(queueName)
            End If
        End Sub
#End If
        Private Sub AddQueuePermissions(ByVal queueName As String, ByVal userName As String)
            If Not String.IsNullOrEmpty(queueName) Then
                Dim accessQueuePrivilege = String.Format(CultureInfo.InvariantCulture, "{0}{1}", queueName, PrivilegeConstants.QueuePrivilegeSuffix)
                Me.userPrivilegesRepository.AddPrivilegeToUser(userName, accessQueuePrivilege)
            End If
        End Sub

        Private Sub RemoveAllQueuePermissions(ByVal queueName As String)
            If Not String.IsNullOrEmpty(queueName) Then
                Dim publicQueuePrivilege = String.Format(CultureInfo.InvariantCulture, "{0}{1}", queueName, PrivilegeConstants.PublicQueuePrivilegeSuffix)
                Me.userPrivilegesRepository.DeletePublicPrivilege(publicQueuePrivilege)

                Dim accessQueuePrivilege = String.Format(CultureInfo.InvariantCulture, "{0}{1}", queueName, PrivilegeConstants.QueuePrivilegeSuffix)
                Me.userPrivilegesRepository.DeletePrivilege(accessQueuePrivilege)
            End If
        End Sub
    End Class
End Namespace